<template>
	<view class="">
		<view class="" @touchmove.stop.prevent="a = false" @catchtouchmove="a = false"  >
			<view class="" style="" >
				<u--image :showLoading="true" :src="image"  @click.native="preview(image)"  mode="aspectFill" width="750rpx" height="380rpx" ></u--image>
				 <view class="bottom" :class="cssTran ? 'closeCss' : 'openCss'"  >
				 	<!-- <view class="num">{{indexCurrent}} / {{detail.images.length}}</view> -->
				 	<view class="nav-box"> 
				 		<view class="nav-tab" @click="collectClick()">
				 			<u-icon :name="isColl?'/static/icon/coll_art.png':'/static/icon/coll.png'"  size="42rpx"></u-icon>
				 			<text>{{isColl?'已收藏':'收藏'}}</text>
				 		</view>
				 		<view class="nav-tab" @click="winClick(detail._id)">
				 			<u-icon name="/static/icon/duihuan.png"  size="42rpx"></u-icon>
				 			<text>下载</text>
				 		</view>
				 		<view class="nav-tab" @click="zanClick(isZan)">
				 			<u-icon :name="isZan?'/static/icon/zan_art.png':'/static/icon/zan.png'"  size="42rpx"></u-icon>
				 			<text>{{isZan?'已点赞':'点赞'}}</text>
				 		</view>
				 		<view class="nav-tab">
				 			<u-icon name="/static/icon/shares.png"  size="42rpx"></u-icon>
				 			<text>分享</text>
				 			<button open-type="share" style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;opacity: 0;"></button>
				 		</view>
				 	</view>
				 </view>
				 <view>
					<view class="" v-if="false">
						<u-row>
							<u-col span="2" align="center">
								<u-avatar  src="https://cdn.uviewui.com/uview/album/7.jpg"></u-avatar>
							</u-col>
							<u-col span="10">
								<u-row>
									<u-col span="8" justify="start">
									 
											<u--text block text="周大哥  ·五天前" size="18rpx" color="#9e9e9e"></u--text>
									 
									</u-col>
									<u-col span="2">
										<!-- <u--text text="" size="18rpx" color="#9e9e9e"></u--text> -->
									</u-col>
									<u-col span="2"></u-col>
								</u-row>
								<u-row>
									<u--text block text="真好看" size="30rpx" ></u--text>
								</u-row>
							</u-col>
						</u-row>
					</view>
				 </view>
			</view>

			<!-- <view v-if="tipsShow" style="position: absolute;top: 0;left: 0;width: 100vw;height: 100vh;z-index: 11;" @click="tipsClick">
				<image src="../../static/tips.png" style="width: 100%;height: 100%;display: flex;" mode="aspectFill"></image>
			</view> -->
			
			<!-- <models v-if="loginShow" title="为了更好的玩机体验，快去授权登录吧" btnText="授权登录" @save="getUserInfo" @close="loginShow = false"></models> -->
			
			<models v-if="downShow" :title="downTitle" :btnText="'看广告领 '+adIntegral+' 积分'" :authorize="false" @close="downShow = false" @save="adClick"></models>
		
			<models v-if="signShow"
			:authorize="false" 
			:title="signTitle"
			btnText="知道了" 
			closeText=" " 
			@save="signShow = false"></models>
			
			<models v-show="adShow"
			:authorize="false" 
			:ad="true" 
			title="已成功保存到相册，别忘了分享给朋友哦！"
			btnText="分享给好友" 
			closeText="暂时不用" 
			@save="adShow = false"
			@close="adShow = false"></models>
		</view>
		<!-- <view class="loading_page" v-show="loadFlag"><image src="/static/loading/loading.gif"></image></view> -->
	</view>
</template>

<script>
let videoAd = null;

const db =   uniCloud.database()
var w = uni.getSystemInfoSync().windowWidth;
var h = uni.getSystemInfoSync().windowHeight;
	import {
		mapMutations,
		mapGetters,
		mapActions
	} from 'vuex';
import models from '@/components/model/model.vue'
export default {
	components: {
		models
	},
	data() {
		return {
			image:"",
			loadFlag: true,
			loginShow: false,
			detail: {},
			
			adIntegral: 0,
			
			downShow: false,
			downIntegral: 0,
			downTitle: '',
			downBtn: '',
			adShow: false,
			
			isColl: false,
			isZan: false,
			zanStatus: true,
			collStatus: true,
			
			cssTran: false,
			indexCurrent: 1,
			activeCurrent: 0,
			
			signShow: false,
			signTitle: '',
			w: w,
			h: h,
		}
	},
	computed:{
		...mapGetters({
			'userInfo': 'user/info',
			'hasLogin': 'user/hasLogin',
		}),
	},
	async onLoad({id,index,images}) {
		var that = this
		 this.id=id
		if(images){
			 that.image = images
			// that.image = encodeURIComponent(images)
			console.log('image>>>',that.image,id)
			that.getDetail(id)
		}else{
			await that.getDetail(id)
		}
		// await that.getConfig()
		 
		if(that.userInfo._id){
			console.log(111)
			that.getIsZan()
			that.getIsColl()
			
			// that.getUser()
		}
		// that.adLoad()
		that.loadFlag = false
	},
	methods: {
		async getDetail(id){ 
			var that = this  
			let detail = await uniCloud.callFunction({
				name: 'query_map',
				data: {
					dbName: "myou-imgs",
					id: id	
				},
			})
		
			that.detail = detail.result
			console.log("detail.result",detail.result) 
			if(!that.detail){
				uni.showToast({
					title: '壁纸不存在',
					icon: 'none',
					duration: 1500
				});
				setTimeout(function(){
					uni.navigateBack()
				},1500)
				return
			}else{
				that.image = detail.result.image
				let zan = detail.result.zan
				if(!zan){
					that.zanStatus = false
				}
				if(that.userInfo._id && zan  && zan.indexOf(that.userInfo._id <0)){
					that.zanStatus = false
				}else{
					console.log('没有点赞')
				}
			}
			// that.addView(id)
		},
		async getConfig(){
			let that = this
			return
			let config = await uniCloud.callFunction({
				name: 'config_map',
				data: {
					'keys': ['downIntegral', 'adIntegral']
				},
			})
			if(config.result.success) {
				that.downIntegral = parseInt(config.result.data[0])
				that.adIntegral = parseInt(config.result.data[1])
			}
		},
		async getIsZan(){

			let count = await uniCloud.callFunction({
				name: 'query_count',
				data: {
					dbName: "myou-imgs",
					filter: {
						"_id": this.id,
						"zan.user_id": this.userInfo._id
					}
				},
			})
			this.zanStatus = false
			console.log('zan',count.result)
			 
			if(count.result > 0) this.isZan = true
		},
		async getIsColl(){
			var that = this
			let filter = {
				'user_id' :that.userInfo._id,
				'img_id':that.id,
				col:true
			}
			console.log("getIsColl" ,filter)
			let list = await db.collection('myou-img-ect').where(filter).get()
			console.log('list',list)
			if(list.result.data.length > 0) this.isColl = true
			// this.col_id = list.result.data[0]._id
			// console.log("getIsColl",this.col_id)
		 
			// this.collStatus = false
			// if(count.result > 0) this.isColl = true
		},
		async winClick(){
			var that = this
			if(!that.vuex_user){
				that.loginShow = true
				return
			}
			
			if(that.downIntegral > 0){
				var integral = that.vuex_user.integral
				if(integral < that.downIntegral){
					that.downShow = true
					that.downTitle = "<p style='font-weight: 550;font-size: 16px;'>下载需要 "+that.downIntegral+" 积分</p><p style='padding-top: 10px;'>您当前仅有<span class='num'>"+integral+"</span>积分，无法下载当前作品，快去赚积分吧~</p>"
					return
				}
				
				uni.showLoading({
					mask: true,
					title: '保存中...'
				})
				
				let query = await uniCloud.callFunction({
					name: 'place_order',
					data: {
						userId: that.vuex_user._id,
						coverId: that.detail._id,
						integral: that.downIntegral,
						index: that.indexCurrent-1
					},
				})
				if(query.result.success){
					// 下载成功 请求用户积分
					that.getUser()
					// 获取图片信息
					var url = that.detail.images[that.indexCurrent-1]
					var extension = url.substring(url.lastIndexOf('.') + 1)
					let fileName = new Date().valueOf();
					
					uni.downloadFile({
						url: url,
						filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.' + extension,
						success: (res) => {
							var benUrl = res.filePath
							//图片保存到本地相册
							uni.saveImageToPhotosAlbum({
								filePath: benUrl,
								//授权成功，保存图片
								success: function(data) {
									uni.hideLoading()
									that.adShow = true
								},
								//授权失败
								fail: function(err) {
									if (err.errMsg) {
										//重新授权弹框确认
										uni.showModal({
											title: '提示',
											content: '无权限，请打开下载权限后再试！',
											showCancel: false,
											success(res) {
												if (res.confirm) {
													//重新授权弹框用户点击了确定
													uni.openSetting({
														//进入小程序授权设置页面
														success(settingdata) {
															if (settingdata.authSetting['scope.writePhotosAlbum']) {
																//用户打开了保存图片授权开关
																uni.saveImageToPhotosAlbum({
																	filePath: benUrl,
																	success: function(data) {
																		uni.hideLoading()
																		that.adShow = true
																	}
																});
															} else {
																//用户未打开保存图片到相册的授权开关
																uni.showModal({
																	title: '温馨提示',
																	content: '授权失败，请稍后重新获取',
																	showCancel: false
																});
															}
														}
													});
												}
											}
										});
									}
									uni.hideLoading()
								}
							});
						},
						fail: (error) => {
							console.log(error)
						}
					})
				}else{
					uni.showToast({
						mask: true,
						icon: 'none',
						title: query.result.msg,
						duration: 1000
					})
				}
			}else{
				// 获取图片信息
				var url = that.detail.images[that.indexCurrent-1]
				var extension = url.substring(url.lastIndexOf('.') + 1)
				let fileName = new Date().valueOf();
				
				uni.downloadFile({
					url: url,
					filePath: wx.env.USER_DATA_PATH + '/' + fileName + '.' + extension,
					success: (res) => {
						var benUrl = res.filePath
						//图片保存到本地相册
						uni.saveImageToPhotosAlbum({
							filePath: benUrl,
							//授权成功，保存图片
							success: function(data) {
								uni.hideLoading()
								that.adShow = true
							},
							//授权失败
							fail: function(err) {
								if (err.errMsg) {
									//重新授权弹框确认
									uni.showModal({
										title: '提示',
										content: '无权限，请打开下载权限后再试！',
										showCancel: false,
										success(res) {
											if (res.confirm) {
												//重新授权弹框用户点击了确定
												uni.openSetting({
													//进入小程序授权设置页面
													success(settingdata) {
														if (settingdata.authSetting['scope.writePhotosAlbum']) {
															//用户打开了保存图片授权开关
															uni.saveImageToPhotosAlbum({
																filePath: benUrl,
																success: function(data) {
																	uni.hideLoading()
																	that.adShow = true
																}
															});
														} else {
															//用户未打开保存图片到相册的授权开关
															uni.showModal({
																title: '温馨提示',
																content: '授权失败，请稍后重新获取',
																showCancel: false
															});
														}
													}
												});
											}
										}
									});
								}
								uni.hideLoading()
							}
						});
					},
					fail: (error) => {
						console.log(error)
					}
				})
			}
		},
		backClick(){
			uni.navigateBack()
		},
		preview(src){
			console.log('预览',src)
			uni.previewImage({
				urls:[src],
				longPressActions:{
					itemList:['保存'],
					success:res=>{
						console.log(res)
					}
				},
				success:res=>{
					console.log('预览的',res)
				}
			})
		},
		async collectClick() {
			console.log(this.userInfo)
			console.log(this.id,this.image)
			if(this.isColl){
				//取消
				let result = await db.collection('myou-img-ect').where({
					user_id:this.userInfo._id,
					img_id:this.id,
					col:true,
					img_url:this.image,
					type:'col'
				}).remove().then(res=>{
					console.log('取消收藏',res)
					 if(res.result.deleted === 0){
					 	return {
					 		success: false,
					 		msg: '删除失败'
					 	}
					 }else{
						 console.log('取消成功')
						 this.isColl = false
					 }
				})

			}else{
				this.isColl = true
				let s = await db.collection('myou-img-ect').add(
				{
					user_id:this.userInfo._id,
					img_id:this.id,
					col:true,
					img_url:this.image,
					type:'col'
				}).then(r=>{
					console.log('状态',r)
					
				})
			}
		
		 
		  // let list = db.where({
			 //  user_id:this.userInfo._id,
			 //  img_id:this.id,
			 //  col:true
		  // }).get()
		  // console.log(list)
		 return
			var that = this
			if(!that.userInfo){
				that.loginShow = true
				return
			}

			// if(that.collStatus){
			// 	uni.showToast({
			// 		icon: 'none',
			// 		title: '太快啦，歇一会再试试',
			// 		mask: true,
			// 		duration: 1000
			// 	})
			// 	return
			// }
			// that.collStatus = true
			// 先显示  再请求 视觉上更适应
			that.isColl = !that.isColl

			let coll = await uniCloud.callFunction({
				name: 'zan_and_coll',
				data: {
					dbName: 'myou-img-ect',
					type: 'coll',
					userId: that.userInfo._id,
					filter: {
						"_id": that.id,
						"user_id": that.userInfo._id, 
					}
				},
			})
			if(!coll.result.success){
				// 更新失败
				uni.showToast({
					mask: true,
					icon: 'none',
					title: coll.result.msg,
					duration: 2000
				})
				that.isColl = !that.isColl
			}
			setTimeout(function(){
				that.collStatus = false
			},5000)
		},
		async zanClick(zan){
			var that = this
			if(!that.userInfo){
				that.loginShow = true
				return
			}

			var timestamp = new Date().getTime()
			if(zan){
				uni.showToast({
					icon: 'none',
					title: '你已经点过赞啦~',
					mask: true,
					duration: 1000
				})
			}else{
				if(that.zanStatus){
					uni.showToast({
						icon: 'none',
						title: '太快啦，歇一会再试试',
						mask: true,
						duration: 1000
					})
					return
				}
				that.zanStatus = true
				// 先显示  再请求 视觉上更适应
				that.isZan = !that.isZan
			
			 
				let zan = await uniCloud.callFunction({
					name: 'zan_and_coll',
					data: {
						dbName: 'myou-imgs',
						type: 'zan',
						userId: that.userInfo._id,
						filter: {
							"_id": that.detail._id,
							"zan.user_id": that.userInfo._id
						}
					},
				})
				  
				if(!zan.result.success){
					// 更新失败
					uni.showToast({
						mask: true,
						icon: 'none',
						title: zan.result.msg,
						duration: 2000
					})
					that.isZan = !that.isZan
				}
			}
			setTimeout(function(){
				that.zanStatus = false
			},5000)
		},
		cssClick() {
			this.cssTran = !this.cssTran
		},
		swiperChange(e){
			this.indexCurrent = e.detail.current + 1
		},
		async addView(id){
			let result = await uniCloud.callFunction({
				name: 'view_raise',
				data: {
					coverId: id
				}
			})
		},
		adClick(){
			var that = this
			if(!that.vuex_user){
				that.loginShow = true
				return
			}
			if (videoAd) {
				videoAd.show().catch(err => {
				// 失败重试
				// console.log("广告拉去失败")
				videoAd.load().then(() => videoAd.show())
				})
			}
		},
		adLoad(){
			var that = this
			if (wx.createRewardedVideoAd) {
				// 加载激励视频广告
				// #ifdef MP-QQ
				videoAd = wx.createRewardedVideoAd({
					adUnitId: "cbe2baa6cdb9b4f2c75269d000476ee6"
				});
				// #endif
				// #ifdef MP-WEIXIN
				videoAd = wx.createRewardedVideoAd({
					adUnitId: "adunit-c99bff2627193131"
				});
				// #endif
				//捕捉错误
				videoAd.onError(err => {
					// 进行适当的提示
					console.log('videoAd onError', res);
				});
				// 监听关闭
				videoAd.onClose(status => {
					that.downShow = false
					if ((status && status.isEnded) || status === undefined) {
						// 正常播放结束，下发奖励
						if(that.userInfo){
							that.userIntegral()
						}
					} else {
						// 播放中途退出，进行提示
						console.log('中途退出')
					}
				});
			}
		},
		//用户积分
		async userIntegral(){
			var that = this
			uni.showLoading({
				mask: true,
				title: '加载中...'
			})
			let data = await uniCloud.callFunction({
				name: 'user_integral',
				data: {
					userId: that.userInfo._id
				},
			})
			uni.hideLoading()
			if(data.result.success){
				that.getUser()
				that.signTitle = "<p style='font-weight: 550;font-size: 16px;'>观看成功</p><p style='padding-top: 10px;'>获得<span class='num'>"+data.result.integral+"</span>积分</p>"
				that.signShow = true
			}
		},
		async getUser(){
			let that = this
			let detail = await uniCloud.callFunction({
				name: 'query_map',
				data: {
					dbName: "wx_user",
					id: that.vuex_user._id
				},
			})
			that.$u.vuex('vuex_user', detail.result)
		},


		// 登录
		getUserInfo(){
			var that = this
			wx.getUserProfile({
			  desc: '更新您的个人信息',
			  success: (res) => {
				  that.name = res.userInfo.nickName; //昵称
				  that.avatar = res.userInfo.avatarUrl; //头像
				  // 成功后进行登录,获取code
				  that.wxlogin();
			  },
			  fail(err){
				  uni.showToast({
				  	icon: 'none',
				  	title: '授权失败',
				  	duration: 1500
				  })
			  }
			})
		},
		//已经授权，自动登录
		async wxlogin() {
			let that = this;
			uni.showLoading({
				title: '登录中...'
			});
			uni.login({
				provider: 'weixin',
				success: function(loginRes) {
					let code = loginRes.code;
					that.wxloginres(code);
				},
			});

		},
		//登录后提交服务器获取进一步信息
		async wxloginres(wxcode) {
			let that = this;

			var userId = uni.getStorageSync('userId')

			var mptype
			// #ifdef MP-WEIXIN
				mptype = 'wx'
			// #endif
			// #ifdef MP-QQ
				mptype = 'qq'
			// #endif
			
			let authorize = await uniCloud.callFunction({
				name: 'user_authorize',
				data: {
					name: that.name,
					avatar: that.avatar,
					mptype: mptype,
					code: wxcode,
					userId: userId,
				},
			})
			if(authorize.result.success){
				that.$u.vuex('vuex_user',authorize.result.data)
				// 登陆成功  获取收藏点赞
				that.getIsZan()
				that.getIsColl()
				uni.showToast({
					icon: 'none',
					mask: true,
					title: '登录成功',
					duration: 1500
				})
				uni.removeStorageSync('userId')
			}else{
				uni.showToast({
					icon: 'none',
					mask: true,
					title: authorize.result.msg,
					duration: 1500
				})
			}
			that.loginShow = false
		},
	},
	onShareAppMessage(res) {
		var that = this
		setTimeout(function(){
			that.adShow = false
		},2000)
		return {
			title: '送你一张超级好看的壁纸~',
			imageUrl: that.image,
			path: '/pages/index/index?userId='+that.userInfo._id+'&detailId='+that.id+'&images'+that.image
		}
	},
	onShareTimeline(res) {
		return {
			title: '我等风也等你，近听水无声~',
			imageUrl: '/static/share_bg.jpg',
			path: '/pages/index/index'
		}
	}
}
</script>
<style lang="scss">
	.bottom {
		// position: fixed;
		// left: 4%;
		// right: 0;
		margin: 10rpx auto;
		width: 92%;
		height: 82rpx;
		box-shadow: 0 0px 8px rgba(0, 0, 0, 0.06);
		background: rgba(0, 0, 0, 0.94);
		border-radius: 49px;
		z-index: 10;
		opacity: 0.8;
		.num{
			position: absolute;
			top: -20rpx;
			top: -70rpx;
			left: 44%;
			background: rgba(0,0,0,0.6);
			color: #FFF;
			padding: 4rpx 20rpx;
			font-size: 12px;
			border-radius: 36px;
		}
	}

	.nav-tab {
		position: relative;
		
		width: 100%;
		height: 88rpx;
		font-size: 12px;
		color: #D8D8D8;
		font-weight: 400;

		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	.nav-box {
		/* position: absolute; */
		display: flex;
		flex-direction: row;
		justify-content: space-around;
		width: 100%;
		box-sizing: border-box;
	}

	.openCss {
		animation-name: openLinear;
		animation-duration: 0.8s;
		animation-iteration-count: 1;
		bottom: 40px;
	}

	@keyframes openLinear {
		0% {
			transform: translateY(92px);
		}
		100% {
			transform: translateY(0px);
		}
	}

	.closeCss {
		animation-name: closeLinear;
		animation-duration: 0.8s;
		animation-iteration-count: 1;
		bottom: -52px;
	}

	@keyframes closeLinear {
		0% {
			transform: translateY(-92px);
		}
		100% {
			transform: translateY(0px);
		}
	}
	
	.u-indicator-item-number {
		padding: 6rpx 16rpx;
		line-height: 1;
		background-color: rgba(0, 0, 0, 0.3);
		border-radius: 100rpx;
		font-size: 26rpx;
		color: rgba(255, 255, 255, 0.8);
	}
</style>